package com.kaiwukj.android.ufamily.mvp.ui.widget.home;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kaiwukj.android.ufamily.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 带尾部标签的TextView
 *
 * @author huiwings
 * @date 2019-11-6
 */
public class TagTextView extends RelativeLayout {

    public static final int WORD_LENGTH = 26;//设置一个单词最长不能超过26个字符

    private int maxLine = 100;

    private TextView mTextView;
    private TextView mTagTextView;

    private int mTextColor;
    private int mTagTextColor;

    private float mTextSize;
    private float mTagTextSize;

    private boolean needTagEnd = true;//溢出是否需要省略号

    private FlowLayout mFlowLayout;

    private Context mContext;

    private int mWidth;

    private boolean hasTag = false;

    private String mText = "";
    private String mTagText;

    private boolean isFirst = true;

    private OnTagClickListener onTagClickListener;

    public void setOnTagClickListener(OnTagClickListener onTagClickListener) {
        this.onTagClickListener = onTagClickListener;
    }


    public TagTextView(Context context) {
        this(context, null);
    }

    public TagTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TagTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TagTextView);

        mTextColor = typedArray.getInt(R.styleable.TagTextView_textColor, 0);
        mTagTextColor = typedArray.getInt(R.styleable.TagTextView_tagTextColor, 0);
        mTextSize = typedArray.getDimension(R.styleable.TagTextView_textSize, 12);
        mTagTextSize = typedArray.getDimension(R.styleable.TagTextView_tagTextSize, 12);
        maxLine = typedArray.getInt(R.styleable.TagTextView_maxLine, maxLine);
        needTagEnd = typedArray.getBoolean(R.styleable.TagTextView_tagEnd,true);

        typedArray.recycle();

        init();
    }

    public TagTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        this(context, attrs, defStyleAttr);
    }

    private void init() {

        mFlowLayout = new FlowLayout(mContext);
        this.addView(mFlowLayout);

        mTextView = getTextView(mTextSize);
        //mTextView.setTextColor(mTextColor);
        //mTextView.setTextSize(mTextSize);

        mTagTextView = new TextView(mContext);
        mTagTextView.setTextColor(mTagTextColor);
        mTagTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTagTextSize);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (isFirst) {
            isFirst = false;
            mWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
            drawText();
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void drawText() {
        int widthScreen = mWidth;
        float lineWidth = 0;//计算一行的宽度
        int index = 0;//记住每行开头的下标索引
        int rows = 0;//计算行数
        int isNullCharIndex = 0;//英文
        int lastRowCount = 0;

        List<String> strs = new ArrayList<>();
        for (int i = 0; i < mText.length(); i++) {
            float charWidth = getCharWidth(mTextView, mText.charAt(i));

            if (hasTag) {
                lastRowCount = (int) ((mWidth - mTagText.length() * charWidth) / charWidth);
            } else {
                lastRowCount = (int) (mWidth / charWidth);
            }

            if (lineWidth + charWidth <= widthScreen) {
                lineWidth += charWidth;
                if (mText.charAt(i) == ' ') {
                    isNullCharIndex = i;
                }

                //防止英文字符之间不是连续的
                if (!isA_z(mText.charAt(i))) {
                    isNullCharIndex = i;
                }
                if (isNullCharIndex + WORD_LENGTH < i) {//如果连续15个字符还是没有空格就直接截断
                    isNullCharIndex = i;
                }


            } else {
                if (mText.length() - 1 >= i + 1 && isA_z(mText.charAt(i))) {
                    i = isNullCharIndex;
                    if (mText.length() != i) {
                        strs.add(mText.substring(index, i + 1));
                        index = i + 1;
                        lineWidth = 0;
                        //lineWidth += charWidth;
                        rows++;
                    }
                    continue;
                }

                if (mText.length() != i) {
                    strs.add(mText.substring(index, i));
                    index = i;
                    lineWidth = 0;
                    lineWidth += charWidth;
                    rows++;
                }
            }

            //第一种情况：文本未超出
            if (rows <= maxLine && mText.length() - 1 == i) {
                strs.add(mText.substring(index, i + 1));//加最后一行
                for (int j = 0; j < strs.size(); j++) {
                    TextView textView = new TextView(mContext);
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
                    textView.setTextColor(mTextColor);
                    textView.setText(strs.get(j));
                    //textView.setBackgroundColor(Color.RED);
                    mFlowLayout.addView(textView);
                }
                addTagView();
                break;
            }

            //&& index + (mRowSize / 3 * 2) == i
            //第二种情况：文本超出
            if (rows == maxLine - 1 && (index + (lastRowCount / 5 * 4)) == i) {
                String line = mText.substring(index, i + 1);
                strs.add(line);//加最后一行
                if(needTagEnd){
                    strs.add("...");
                }
                for (int j = 0; j < strs.size(); j++) {
                    TextView textView = new TextView(mContext);
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
                    textView.setText(strs.get(j));
                    textView.setTextColor(mTextColor);
                    //textView.setBackgroundColor(Color.BLUE);
                    mFlowLayout.addView(textView);
                }
                addTagView();
                break;
            }
        }

    }

    private void addTagView() {
        if (hasTag) {
            mTagTextView.setText(mTagText);
            mTagTextView.setOnClickListener(v -> {
                if (onTagClickListener != null) {
                    onTagClickListener.onClick(v);
                }
            });
            mFlowLayout.addView(mTagTextView);
        }
    }

    private float getCharWidth(TextView textView, char c) {
        textView.setText(String.valueOf(c));
        textView.measure(0, 0);
        return textView.getMeasuredWidth();
    }

    /**
     * 临时文本控件，用于计算每个字符所占的空间大小，主要是宽度
     *
     * @param size
     * @return
     */
    private TextView getTextView(float size) {
        TextView textView = new TextView(mContext);
        textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        return textView;
    }

    /**
     * 判断时候是英文字母
     *
     * @param ch
     * @return
     */
    private boolean isA_z(char ch) {
        if ('A' <= ch && ch <= 'Z' || 'a' <= ch && ch <= 'z') {
            return true;
        }
        return false;
    }

    public void setText(String text) {
        if (!TextUtils.isEmpty(text)) {
            mText = text;
            //drawText();
            requestLay();
        }
    }

    public void setTagText(String text) {
        if (!TextUtils.isEmpty(text)) {
            hasTag = true;
            mTagText = text;
            requestLay();
        }
    }

    private void requestLay() {
        isFirst = true;
        mFlowLayout.removeAllViews();
        requestLayout();
        invalidate();
    }

    public interface OnTagClickListener {
        void onClick(View v);
    }


}
